package com.fireline.beauty;

import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

import com.fireline.beauty.jdbc.SqliteJdbcImpl;
import com.zgw.fireline.base.common.Assert;
import com.zgw.fireline.base.dataset.Dataset;
import com.zgw.fireline.base.frame.FunctionDialog;
import com.zgw.fireline.base.frame.IFunction;

public class ContextHelp {
	public static String getUserName() {
		return "admin";
	}

	/**
	 * 在一块面板上构建一个功能界面
	 * */
	public static Control showFunction(Composite parent, IFunction fun) {
		return fun.createControl(parent);
	}

	public static Control showFunction(Composite parent, String functionId) {
		return getFunction(functionId).createControl(parent);
	}

	/**
	 * 弹出一个功能窗口
	 * */
	public static void OpenFunction(Shell shell, IFunction fun, Point size) {
		FunctionDialog dlg = new FunctionDialog(shell, fun);
		dlg.open();
	}

	/**
	 * 弹出一个功能窗口
	 * */
	public static void OpenFunction(Shell shell, String id, Point size) {
		OpenFunction(shell, getFunction(id), size);
	}

	public static IFunction getFunction(String id) {
		Dataset sysFuns = new Dataset(
				"select * from systemFunction where id=?",
				SqliteJdbcImpl.INSTANCE);
		sysFuns.setParam(0, id);
		sysFuns.update();
		sysFuns.setSelected(0);
		String className = sysFuns.getString("class");
		Assert.isNotNull(className, "功能： " + id + "不存在对应的Class");
		try {
			Class cla = Class.forName(className);
			Assert.isTrue(IFunction.class.isAssignableFrom(cla), "功能： " + id
					+ " 对应Class(" + className + ") 不是IFunction 的实现类");
			return (IFunction) cla.newInstance();
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("功能： " + id + "对应Class(" + className
					+ ") 未找到", e);
		} catch (InstantiationException e) {
			throw new RuntimeException("功能： " + id + " 对应Class(" + className
					+ ")未能实例化  ,检查是否存在无参构造函数", e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException("功能： " + id + " 对应Class(" + className
					+ ") 无法访问", e);
		}
	}
	
	public static Dataset getFunctions(String type) {
		Dataset sysFuns = new Dataset(
				"select * from systemFunction where type=?",
				SqliteJdbcImpl.INSTANCE);
		sysFuns.setParam(0, type);
		sysFuns.update();
		return sysFuns;
	}
}
